package com.example.gcmtest1;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.DefaultClientConnection;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.UrlQuerySanitizer;
import android.opengl.Visibility;
import android.preference.Preference;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class GoogleWebViewClient extends WebViewClient {
	
	private String logName = "GoogleWebViewClient";
	private GoogleWebView parent;
	
	
	public GoogleWebViewClient(GoogleWebView parent) {
		this.parent = parent;
		
	}
	
	@Override
	public void onPageFinished(WebView view, String url) {
		Log.d(logName, "onPageFinished, url=" + url);
		
		if (url.startsWith("http://localhost")) {
			UrlQuerySanitizer qq = new UrlQuerySanitizer(url);
			
			String error = "";
			if (qq.getValue("error") != null) {
				error = qq.getValue("error");
				Log.e(logName, "error=" + error);
				
				
			} else {
				String state = qq.getValue("state");
				String code = qq.getValue("code");
				
				Log.d(logName, "state=" + state);
				Log.d(logName, "code=" + code);
				
				this.exchangeToken(view, code);	
				this.parent.lblResult.setText("Authenticated");
				this.parent.layoutMain.removeView(this.parent.webview1);
			}
			
			
		}
		
		//view.setVisibility(View.INVISIBLE);
	}
	
	private void exchangeToken(WebView view, String code) {
		String scope = "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile";
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost("https://accounts.google.com/o/oauth2/token");
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("code", code));
			nameValuePairs.add(new BasicNameValuePair("client_id", GoogleWebView.CLIENT_ID));
			nameValuePairs.add(new BasicNameValuePair("client_secret", GoogleWebView.CLIENT_SECRET));
			nameValuePairs.add(new BasicNameValuePair("grant_type", "authorization_code"));
			nameValuePairs.add(new BasicNameValuePair("redirect_uri", "http://localhost"));
			//nameValuePairs.add(new BasicNameValuePair("response_type", "code"));
			
			
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpClient.execute(httpPost);
	        
	        String ret = EntityUtils.toString(response.getEntity());
	        Log.d(logName, ret);
	        
	        view.loadData(ret, "text/html", "UTF-8");
	        
	        JSONObject jsObj = new JSONObject(ret);
	        String accessToken = jsObj.getString("access_token");
	        String refreshToken = jsObj.getString("refresh_token");
	        Log.d(logName, "accessToken=" + accessToken);
	        Log.d(logName, "refreshToken=" + refreshToken);
	        
	        this.parent.setAccessToken(accessToken);
	        this.parent.setRefreshToken(refreshToken);
	        
	        SharedPreferences pref = this.parent.getPreferences(Context.MODE_PRIVATE);
	        pref.edit().putString("accessToken", accessToken);
	        pref.edit().putString("refreshToken", refreshToken);

		} catch (Exception e) {
			Log.e(logName, "exchangeToken \n" + e.toString());
		}
	}

}
